package com.lee.dhsg.controller;

import com.lee.dhsg.domain.Student;
import com.lee.dhsg.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;


/**
 * 该控制器与学生有关
 * 1、学生登录
 * 2、学生注册
 * 3、退出登录
 * 4、
 *
 * @author Lee
 */

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;


    /**
     * 学生登录
     */
    @RequestMapping("/studentLogin")
    // @ResponseBody //这一个注释的作用：返回字符串直接显示，而不是作为路径
    public String studentLogin(String username, String password, HttpSession session) throws Exception {

        if (password == null || username == null || username.equals("") || password.equals("")) {
            // 当表单数据为空时，登录失败
            return "redirect:index";
        }
        Student student = studentService.login(username, password); // 查询数据库中是否有该学生
        if (student != null) {

            // 登录成功

            // 将学生保存到 session 中
            session.setAttribute("StudentSession", student);

        }

        return "redirect:index";

    }

    /**
     * 退出登录
     */
    @RequestMapping("/studentLogout")
    public String studentOffline(HttpSession session) {
        // 清除保存 StudentSession 的 session
        session.removeAttribute("StudentSession");
        return "redirect:index";
    }

    /**
     * 学生注册
     */
    @RequestMapping("/studentRegister")
    public String studentRegister(String username, String password) throws Exception {
        if (password == null || username == null || username.equals("") || password.equals("")) {
            // 当表单数据为空时，注册失败
            return "redirect:index";
        }
        studentService.register(username, password); // 注册

        // 注册成功后完成登录
        String url = "redirect:studentLogin？&username=" + username + "&password=" + password;
        return url;
    }

}
